<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends CI_Controller {
	function __construct()
	{
		parent::__construct();
        $this->load->model("customers_model", "model", TRUE);
	}

	function login()
	{
		$this->template->set("title", "Login client area");
		$this->template->load("login_view");
	}

	function try_login()
	{

        $this->load->library("form_validation");
        $this->form_validation->set_rules("username", "Username", "trim|required");
        $this->form_validation->set_rules("passwd", "Password", "trim|required");
        if($this->form_validation->Run()===FALSE)
		{
			$data['error'] = validation_errors();
		}
		else{
			$username = $this->input->post("username");
			$password = $this->input->post("passwd");

			//we get user data if username and password match
			$data=$this->model->login($username, $password);
			if(isset($data['user'])){
				$user = $data['user'];

				unset($user['salt']);
			    unset($user['pwd']);

				$userdata['client_logged'] = 1;
				$userdata['cust_id'] = $user['cust_id'];
				$userdata['user'] = $user;
				$this->session->set_userdata($userdata);
	            $data['redirect'] = base_url();
				unset($data['user']);
			}
		}

		$is_front = $this->input->post("is_front");
		if($is_front){$data['alert'] = 1;}

		$this->util->send_json($data);
	}

	function logout()
	{
		$this->session->sess_destroy();
		redirect("");
	}

	function change_password()
	{

   		$this->load->library("form_validation");
        $this->form_validation->set_rules("old_password", "Old Password", "required");
        $this->form_validation->set_rules("new_password", "New Password", "trim|required|matches[re_password]");
        if($this->form_validation->Run()===FALSE)
		{
			$data['error'] = validation_errors();
		}
		else
		{
			$old_password = $this->input->post("old_password");
			$new_password = $this->input->post("new_password");

			$user = $this->session->userdata('user');
			$username = $user['username'];

            $data=$this->model->login($username, $old_password);
			if(isset($data['user'])) //password is ok
			{
				$user = $data['user'];
                $data = $this->model->change_password($username, $new_password, $user['salt']);
			}
		}
		$this->util->send_json($data);

	}


}

/* End of file Auth.php */
/* Location: ./application/controllers/Auth.php */